package com.xzx.masterslave.masterslave.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * 主从数据源配置
 * @author admin
 */
@Configuration
@Slf4j
public class DataSourceConfig {
    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;

    /**
     * 写数据源
     * @return
     */
    @Bean(name = "writeDatasource")
    @Primary
    @ConfigurationProperties(prefix  = "spring.master")
    public DataSource writeDataSource(){
        log.info("writeDataSource初始化成功===> 写数据源");
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    /**
     * 单个读数据源
     * @return
     */
    @Bean(name = "readSource")
    @ConfigurationProperties(prefix = "spring.slave")
    public DataSource readDataSource() {
        log.info("readDataSource初始化成功===> 读数据源");
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    /**
     * 多从数据源 实现简单负载均衡
     * @return
     */
    @Bean("readDataSources")
    public List<DataSource> readDataSources() {
        List<DataSource> list = new ArrayList<>();
        list.add(readDataSource());
        return list;
    }





}
